import React, {useEffect, useState} from "react";
import {Table, Tag, Button, Modal} from "antd";
import axios from "axios";
import {AlertOutlined, DeleteOutlined, ExclamationCircleOutlined, SearchOutlined} from "@ant-design/icons";

const {confirm} = Modal

export default function NewsDraft(props) {
    // Table属性
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '新闻标题',
            dataIndex: 'title',
            key: 'title',
            render: (title, item) => {
                return (
                    <a href={`#/news-manage/preview/${item.id}`}>{title}</a>
                )
            }
        },
        {
            title: '作者',
            dataIndex: 'author',
            key: 'key',
        },
        {
            title: '分类',
            dataIndex: 'category',
            key: 'key',
            render: (category) => {
                return category.title
            }
        },
        {
            title: '操作',
            render: (item) => {
                return (
                    <div>
                        <Button type={"primary"} shape="circle" icon={<SearchOutlined/>} onClick={() => {
                            props.history.push(`/news-manage/update/${item.id}`)
                        }}/>

                        <Button type={"danger"} shape="circle" style={{margin: 10}} icon={<DeleteOutlined/>}
                                onClick={() => confirmMethod(item)}/>

                        <Button type={"success"} shape="circle" icon={<AlertOutlined/>}
                                onClick={() => confirmMethod(item)}/>

                    </div>
                )
            }
        }
    ]
    const {username} = JSON.parse(localStorage.getItem("token"))
    // dataSource
    const [dataSource, setDataSource] = useState([])
    useEffect(async () => {
        let res = await axios.get(`http://localhost:5000/news?author=${username}&auditState=0&_expand=category`)
        const list = res.data
        setDataSource(list)
    }, [])

    //确定是否删除弹框
    const confirmMethod = (item) => {
        confirm({
            title: '确定要删除吗',
            icon: <ExclamationCircleOutlined/>,
            // content: 'Some descriptions',
            async onOk() {
                // console.log('OK');
                await deleteMethod(item)
            },
            onCancel() {
                // console.log('Cancel');
            },
        });
    }

    // 删除函数
    const deleteMethod = async (item) => {
        setDataSource(dataSource.filter(data => data.id !== item.id))
        axios.delete(`http://localhost:5000/news/${item.id}`)
    }
    return (
        <div>
            <Table dataSource={dataSource} columns={columns} pagination={{
                pageSize: 5
            }}
                   rowKey={item => item.id}/>
        </div>
    )
}

